<?php

namespace app\common\lib\exception;
use think\exception\Handle;
use think\Request;
use think\Log;
use think\Exception;
use app\common\lib\exception\ApiException;

class ApiHandleException extends  Handle {

    /**
     * http 状态码
     * @var int
     */
    public $httpCode;
    public $message;
    public $errorCode;

    /**
     * 异常处理机制
     */
    public function render(\Exception $e) {

        if(config('app_debug') == true) {
            return parent::render($e);
        }
        
        if ($e instanceof ApiException) {
            //如果是自定义异常
            $this->httpCode = $e->httpCode;
            $this->message = $e->msg;
            $this->errorCode = $e->code;            
        }else {
            //服务器类型错误
            $this->httpCode = 500;
            $this->errorCode = 999;
            $this->message = '服务器内部错误，无可奉告';
            //todo : 记录日志
            $this->recordErrorLog($e);   
        }
        $request = Request::instance();
        
        return  show($this->errorCode, $this->message, ['request_url'=>$request->url()], $this->httpCode);
    }

    /**
     * 记录错误级别日记
     */
    private function recordErrorLog(\Exception $e)
    {
        Log::init([
			'type' => 'File',
			'path' => LOG_PATH,
			'level' => ['error']
			]);
		Log::record($e->getMessage(),'error');
    }
}